package net.zhuike.novel.app.ui.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.luomi.lm.ad.ADType;
import com.luomi.lm.ad.DRAgent;
import com.luomi.lm.ad.IAdSuccessBack;
import com.umeng.analytics.MobclickAgent;

import net.zhuike.novel.app.R;
import net.zhuike.novel.app.ZhuiKeApplication;
import net.zhuike.novel.app.bean.BookChapterBean;
import net.zhuike.novel.app.bean.BookDetail;
import net.zhuike.novel.app.bean.BookLists;
import net.zhuike.novel.app.bean.BookSit;
import net.zhuike.novel.app.bean.ChapterInfoBean;
import net.zhuike.novel.app.bean.CollBookBean;
import net.zhuike.novel.app.bean.HotReview;
import net.zhuike.novel.app.bean.HotWord;
import net.zhuike.novel.app.bean.Recommend;
import net.zhuike.novel.app.bean.RecommendBookList;
import net.zhuike.novel.app.bean.SitBean;
import net.zhuike.novel.app.bean.local.BookRepository;
import net.zhuike.novel.app.bean.local.SitRepository;
import net.zhuike.novel.app.bean.support.RefreshCollectionIconEvent;
import net.zhuike.novel.app.bean.support.UserSexChooseFinishedEvent;
import net.zhuike.novel.app.common.OnRvItemClickListener;
import net.zhuike.novel.app.manager.CollectionsManager;
import net.zhuike.novel.app.manager.EventManager;
import net.zhuike.novel.app.service.BookReadService;
import net.zhuike.novel.app.service.BookStoreService;
import net.zhuike.novel.app.service.SearchService;
import net.zhuike.novel.app.ui.adapter.RecommendBookListAdapter;
import net.zhuike.novel.app.ui.adapter.TocListAdapter;
import net.zhuike.novel.app.ui.base.Constant;
import net.zhuike.novel.app.ui.utils.FormatUtils;
import net.zhuike.novel.app.ui.utils.RxUtils;
import net.zhuike.novel.app.ui.utils.SharedPreferencesUtil;
import net.zhuike.novel.app.ui.utils.SiteHelper;
import net.zhuike.novel.app.ui.utils.StringUtils;
import net.zhuike.novel.app.ui.utils.ToastUtils;
import net.zhuike.novel.app.ui.view.DrawableCenterButton;
import net.zhuike.novel.app.ui.view.FullyLinearLayoutManager;
import net.zhuike.novel.app.ui.view.TagColor;
import net.zhuike.novel.app.ui.view.UeDialog;
import net.zhuike.novel.app.ui.view.page.TxtChapter;
import net.zhuike.novel.app.ui.view.page.TxtPage;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;
import framework.common.baseui.UeBaseActivity;
import framework.common.easyadpter.glide.GlideRoundTransform;
import framework.common.views.InnerListView;
import framework.common.zanetwork.UeHttpUrl;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.StringsUtil;
import io.reactivex.Single;
import io.reactivex.SingleEmitter;
import io.reactivex.SingleObserver;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by wq on 2017/6/22.
 * 书籍详情
 */
public class BookDetailActivity extends UeBaseActivity implements OnRvItemClickListener<Object> {

    public static String INTENT_BOOK_ID = "bookId";
    public static final String RESULT_IS_COLLECTED = "result_is_collected";
    private static final String TAG = "BookDetailActivity";
    private static final String EXTRA_BOOK_ID = "extra_book_id";
    public static void startActivity(Context context, String bookId) {
        context.startActivity(new Intent(context, BookDetailActivity.class)
                .putExtra(INTENT_BOOK_ID, bookId));
    }

    @Bind(R.id.ivBookCover)
    ImageView mIvBookCover;
    @Bind(R.id.tvBookListAuthor)
    TextView mTvAuthor;
    @Bind(R.id.tvCatgory)
    TextView mTvCatgory;
    TextView menuUpdateTx;
    @Bind(R.id.tvWordCount)
    TextView mTvWordCount;
    @Bind(R.id.tvLatelyUpdate)
    TextView mTvLatelyUpdate;
    @Bind(R.id.btnRead)
    DrawableCenterButton mBtnRead;
    @Bind(R.id.btnJoinCollection)
    DrawableCenterButton mBtnJoinCollection;
    @Bind(R.id.tvLatelyFollower)
    TextView mTvLatelyFollower;
    @Bind(R.id.tvRetentionRatio)
    TextView mTvRetentionRatio;
    @Bind(R.id.tvSerializeWordCount)
    TextView mTvSerializeWordCount;
    @Bind(R.id.tvlongIntro)
    TextView mTvlongIntro;
    @Bind(R.id.tvMoreReview)
    ImageView mTvMoreReview;
    @Bind(R.id.tvRecommendBookList)
    TextView mTvRecommendBookList;
    @Bind(R.id.tvBookListState)
    TextView tvBookListState;
    @Bind(R.id.tipsUpdateTx)
    TextView tipsUpdateTx;
    @Bind(R.id.rvRecommendBoookList)
    InnerListView mRvRecommendBoookList;
    @Bind(R.id.upOrDownBtn)
    ImageView upOrDownBtn;
    @Bind(R.id.muluNumber)
    TextView muluNumber;
    @Bind(R.id.scrollView)
    ScrollView scrollView;
    @Bind(R.id.bookTipsLayout)
    LinearLayout tips;
    @Bind(R.id.ll_layout)
    LinearLayout ll_layout;
    private List<String> tagList = new ArrayList<>();
    private int times = 0;
    private CollBookBean mCollBookBean;
    private RecommendBookListAdapter mRecommendBookListAdapter;
    private List<RecommendBookList.RecommendBook> mRecommendBookList = new ArrayList<>();
    private String bookId;
    private int selectShow = 1;
    private boolean collapseLongIntro = true;
    private Recommend.RecommendBooks recommendBooks;
    private boolean isJoinedCollections = false;
    private Context mContext;
    private List<BookSit.Chapters> mChapterSitList = new ArrayList<>();
    private OkHttpClient mOkHttpClient;
    private List<BookChapterBean> mChapterList = new ArrayList<>();
    private Handler handler = null;
    private SiteHelper helper;
    private String aid = "";
    private static final int REQUEST_READ = 1;
    protected CompositeDisposable mDisposable;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_book_detail);
        showGoBackBtn();
        hiddenFooter();
        menuUpdateTx=(TextView)findViewById(R.id.menuUpdateTxs);
        handler = new Handler();
        mContext = this;
        initDatas();
    }

    public void initDatas() {
        bookId = getIntent().getStringExtra(INTENT_BOOK_ID);
        configViews();
        DRAgent.getInstance().getOpenView(context, ADType.MESSAGE_IMGS, true, new IAdSuccessBack() {

            @Override
            public void onError(final String result) {

            }

            @Override
            public void onClick(String result) {
                // TODO Auto-generated method stub
                // TODO Auto-generated method stub

            }

            @Override
            public void OnSuccess(String result) {
                // TODO Auto-generated method stub

                // TODO Auto-generated method stub


            }

            @Override
            public void OnLoadAd(View view) {
                // TODO Auto-generated method stub
                ll_layout.addView(view);
            }
        });
    }

    public void configViews() {
        scrollView.smoothScrollTo(0,0);
        mRecommendBookListAdapter = new RecommendBookListAdapter(mContext, mRecommendBookList);
        mRvRecommendBoookList.setAdapter(mRecommendBookListAdapter);
        mRvRecommendBoookList.setNestedScrollingEnabled(false);
        mRvRecommendBoookList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                RecommendBookList.RecommendBook recommendBook = mRecommendBookList.get(position);

                BookLists bookLists = new BookLists();
                BookLists.BookListsBean bookListsBean = bookLists.new BookListsBean();
                bookListsBean._id = recommendBook.id;
                bookListsBean.author = recommendBook.author;
                bookListsBean.bookCount = recommendBook.bookCount;
                bookListsBean.collectorCount = recommendBook.collectorCount;
                bookListsBean.cover = recommendBook.cover;
                bookListsBean.desc = recommendBook.description;
                bookListsBean.title = recommendBook.name;
                BookDetailActivity.startActivity(context, recommendBook.id);
                finish();
            }
        });
        getBookDetail(bookId);
        getRecommendBookList(bookId, "1");
    }

    public void showBookDetail(BookDetail data) {
        Glide.with(mContext)
                .load(data.cover)
                .placeholder(R.mipmap.cover_default)
                .transform(new GlideRoundTransform(mContext))
                .into(mIvBookCover);
        setTitleText(data.name);

        mCollBookBean = BookRepository.getInstance().getCollBook(data.id);
        tipsUpdateTx.setText(data.progress);
        tvBookListState.setText("更新状态:" + data.progress);
        mTvAuthor.setText("本书作者: " + String.format(getString(R.string.book_detail_author), data.author));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date dt = new Date(Long.parseLong(data.lastestUpdateTime));
        String sDateTime = sdf.format(dt);
        if (data.progress.equals("连载中")) {
            mTvLatelyUpdate.setText("更新时间 :" + sDateTime);
            mTvWordCount.setText("共计字数 :" +data.words);
        } else {
            mTvLatelyUpdate.setText("完结时间 :" + sDateTime);
            mTvWordCount.setText("最新章节 :" + data.chapterName);
        }
        aid = data.aid;
        times = 0;
        if (data.description != null) {
            mTvlongIntro.setText(Html.fromHtml(data.description));
            int linCount=mTvlongIntro.getLineCount();
            if(linCount>3) {
                upOrDownBtn.setVisibility(View.VISIBLE);
            }else{
                upOrDownBtn.setVisibility(View.GONE);
            }
        } else {
            upOrDownBtn.setVisibility(View.GONE);
        }
        recommendBooks = new Recommend.RecommendBooks();
        recommendBooks.name = data.name;
        recommendBooks.id = data.id;
        recommendBooks.cover = data.cover;
        recommendBooks.lastChapter = data.chapterName;
        recommendBooks.updated = sDateTime;
        recommendBooks.aid = data.aid;
        //判断是否收藏
        if (mCollBookBean != null) {
            initCollection(false);
            isJoinedCollections = true;
        } else {
            mCollBookBean = data.getCollBookBean();
            initCollection(true);
            isJoinedCollections = false;
        }
        Disposable disposable = BookRepository.getInstance()
                .getBookChaptersInRx(bookId)
                .compose(RxUtils::toSimpleSingle)
                .subscribe(
                        (bookChapterBeen, throwable) -> {
                            if (bookChapterBeen.size() > 0) {
                                mChapterList.clear();
                                mChapterList.addAll(bookChapterBeen);
                                mCollBookBean.setBookChapters(mChapterList);
                                handler.post(runnableUi);
                            }else{
                                UeDialog.showprogressDialog(context,"","加载中...",false);
                                getBookMixAToc(mCollBookBean.getId(), mCollBookBean);
                            }
                        }
                );
        if (mDisposable == null) {
            mDisposable = new CompositeDisposable();
        }
        mDisposable.add(disposable);



    }

    @OnClick(R.id.upOrDownBtn)
    public void upOrDown() {
        if (selectShow == 1) {
            selectShow = 2;
            upOrDownBtn.setImageResource(R.mipmap.rank_arrow_up);
            mTvlongIntro.setMaxLines(50);
        } else {
            selectShow = 1;
            upOrDownBtn.setImageResource(R.mipmap.rank_arrow_down);
            mTvlongIntro.setMaxLines(4);
        }
    }

    public void showRecommendBookList(List<RecommendBookList.RecommendBook> list) {
        if (!list.isEmpty()) {
            mTvRecommendBookList.setVisibility(View.VISIBLE);
            mRecommendBookList.clear();
            for(RecommendBookList.RecommendBook book:list){
                if(!bookId.equals(book.id)){
                    mRecommendBookList.add(book);
                }
            }
            mRecommendBookListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("书籍详情");
        MobclickAgent.onResume(context);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("书籍详情");
        MobclickAgent.onPause(context);
    }

    @Override
    public void onItemClick(View view, int position, Object data) {
        if (data instanceof HotReview.Reviews) {
            //BookDiscussionDetailActivity.startActivity(this, ((HotReview.Reviews) data)._id);
        } else if (data instanceof RecommendBookList.RecommendBook) {
            RecommendBookList.RecommendBook recommendBook = (RecommendBookList.RecommendBook) data;

            BookLists bookLists = new BookLists();
            BookLists.BookListsBean bookListsBean = bookLists.new BookListsBean();
            bookListsBean._id = recommendBook.id;
            bookListsBean.author = recommendBook.author;
            bookListsBean.bookCount = recommendBook.bookCount;
            bookListsBean.collectorCount = recommendBook.collectorCount;
            bookListsBean.cover = recommendBook.cover;
            bookListsBean.desc = recommendBook.description;
            bookListsBean.title = recommendBook.name;
            BookDetailActivity.startActivity(context, recommendBook.id);
            finish();
            // SubjectBookListDetailActivity.startActivity(this, bookListsBean);
        }
    }

    @OnClick(R.id.btnJoinCollection)
    public void onClickJoinCollection() {
        if(mChapterList.size()>0) {
            if (!isJoinedCollections) {
                if (mCollBookBean != null) {
                    mCollBookBean.setBookChapters(mChapterList);
                    BookRepository.getInstance()
                            .saveCollBook(mCollBookBean);
                    initCollection(false);
                }
            } else {
                BookRepository.getInstance()
                        .deleteCollBookInRx(mCollBookBean);
                ToastUtils.showToast(String.format(getString(
                        R.string.book_detail_has_remove_the_book_shelf), recommendBooks.name));
                initCollection(true);
            }
        }else{
            handler.post(rUis);
        }
    }

    private void initCollection(boolean coll) {
        if (coll) {
            mBtnJoinCollection.setText(R.string.book_detail_join_collection);
            mBtnJoinCollection.setTextColor(Color.parseColor("#1089DC"));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.ic_add_shlf_btn);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mBtnJoinCollection.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.btn_gray_empy_corns));
            mBtnJoinCollection.setCompoundDrawables(drawable, null, null, null);
            mBtnJoinCollection.postInvalidate();
            isJoinedCollections = false;
        } else {
            mBtnJoinCollection.setText(R.string.book_detail_remove_collection);
            mBtnJoinCollection.setTextColor(Color.parseColor("#1089DC"));
            Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.book_detail_info_del_img);
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            mBtnJoinCollection.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.btn_join_collection_pressed));
            mBtnJoinCollection.setCompoundDrawables(drawable, null, null, null);
            mBtnJoinCollection.postInvalidate();
            isJoinedCollections = true;
        }
    }
     @OnClick(R.id.menuUpdateTxs)
     public void onClickMenu(){
         UeDialog.showprogressDialog(context,"","获取中...",false);
         getBookMixAToc(mCollBookBean.getId(), mCollBookBean);
     }
    @OnClick(R.id.btnRead)
    public void onClickRead() {
        if (mCollBookBean == null) return;
        if(mChapterList.size()>0) {
            Intent intent = new Intent(BookDetailActivity.this, ReadActivity.class);
            intent.putExtra("recommendBooksBean", mCollBookBean);
            intent.putExtra("aid", mCollBookBean.getAid());
            intent.putExtra("isFromSD", false);
            intent.putExtra(ReadActivity.INTENT_SD, isJoinedCollections);
            startActivityForResult(intent, REQUEST_READ);
        }else{
            handler.post(rUis);
        }
    }

    @OnClick(R.id.tvMoreReview)
    public void searchByAuthor() {
        if(mChapterList.size()>0) {
            Intent in = new Intent(BookDetailActivity.this, ReadMenuActivity.class);
            in.putExtra("recommendBooksBean", mCollBookBean);
            in.putExtra("type", "1");
            startActivityForResult(in, 3);
        }else{
            handler.post(rUis);
        }
    }

    @OnClick(R.id.tvlongIntro)
    public void collapseLongIntro() {
        if (collapseLongIntro) {
            mTvlongIntro.setMaxLines(20);
            collapseLongIntro = false;
        } else {
            mTvlongIntro.setMaxLines(4);
            collapseLongIntro = true;
        }
    }

    @OnClick(R.id.tvMoreLayout)
    public void onClickMoreReview() {
        if(mChapterList.size()>0) {
            Intent in = new Intent(BookDetailActivity.this, ReadMenuActivity.class);
            in.putExtra("recommendBooksBean", mCollBookBean);
            in.putExtra("type", "1");
            startActivityForResult(in, 3);
        }else{
            handler.post(rUis);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void getBookDetail(final String bookId) {
        BookStoreService.getBookDetail(context, bookId, new ResponseCallback<BookDetail>() {
            @Override
            public void onSuccess(BookDetail bookDetail) {
                if (bookDetail != null) {
                    tips.setVisibility(View.GONE);
                    aid = bookDetail.aid;
                    showBookDetail(bookDetail);
                    Message msg=new Message();
                    msg.obj=bookDetail;
                    handler.sendMessage(msg);
                }else{
                    tips.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                tips.setVisibility(View.VISIBLE);
            }
        });
    }

    public void getRecommendBookList(final String bookId, final String type) {
        BookStoreService.getRecommendBookList(context, bookId, type, new ResponseCallback<RecommendBookList>() {
            @Override
            public void onSuccess(RecommendBookList bookDetail) {
                List<RecommendBookList.RecommendBook> list = bookDetail.list;
                if (list != null && !list.isEmpty()) {
                    showRecommendBookList(list);
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {

            }
        });
    }



    public void getBookMixAToc(String bookId, CollBookBean collBookBean) {
        BookReadService.getBookMixAToc(context, bookId, new ResponseCallback<BookSit>() {
            @Override
            public void onSuccess(BookSit mixToc) {
                if (mixToc != null) {
                    List<BookSit.Chapters> list = mixToc.mulus;

                    showBookToc(bookId, list, collBookBean);
                }
            }

            @Override
            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
                Toast.makeText(ZhuiKeApplication.getAppContext(), "网络连接不可用", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 加载章节列表
     *
     * @param list
     */
    public void showBookToc(String bookId, List<BookSit.Chapters> list, CollBookBean collBookBean) {
        mChapterSitList.clear();
        if (list != null) {
            mChapterSitList.addAll(list);

            if (mChapterSitList.size() > 0) {
                getChapter(bookId, mChapterSitList.get(0).domain, mChapterSitList.get(0).url, collBookBean);
            }

        }

    }

    private void getChapter(String bookId, String url, String loadUrl, CollBookBean collBookBean) {
        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getChapterRead() + url)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    mChapterList.clear();
                    String str = response.body().string();
                    String headers[] = null;
                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                            handler.post(runnableUis);
                        } else {
                            helper = new SiteHelper(restr);
                            SharedPreferencesUtil.getInstance().putString(bookId+"source"+0,"0");
                            String loadUrls;
                            if (loadUrl.indexOf("https") != -1) {
                                loadUrls = loadUrl;
                            } else {
                                if (loadUrl.indexOf("qidian.com") != -1) {
                                    loadUrls = loadUrl.replace("http", "https");
                                } else {
                                    loadUrls = loadUrl;
                                }
                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        Map<String, Object> contexts = new HashMap<String, Object>();
                                        contexts.put("aid", aid);
                                        contexts = helper.executeMulu(contexts, loadUrls);//章节经常性获取不到,故需循环获取
                                        int i = 0;
                                        while (true) {
                                            Object[] chapters = (Object[]) contexts.get("chapters");
                                            if (chapters != null) {
                                                handler.post(vun);
                                                for (Object o : chapters) {
                                                    com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                                    if (!cJson.getString("vip").equals("true")) {
                                                        BookChapterBean chapterBean = new BookChapterBean();
                                                        chapterBean.setBookId(bookId);
                                                        chapterBean.setLink(cJson.getString("url"));
                                                        chapterBean.setTitle(cJson.getString("name"));
                                                        mChapterList.add(chapterBean);
                                                    }
                                                }

                                                if(mChapterList.size()>0) {
                                                    handler.post(runnableUi);
                                                    mCollBookBean.setBookChapters(mChapterList);
                                                    //如果是更新加载，那么重置PageLoader的Chapter
                                                    BookRepository.getInstance()
                                                            .saveBookChaptersWithAsync(mChapterList);
                                                    SitBean sitBean=new SitBean();
                                                    sitBean.setId(bookId);
                                                    sitBean.setUrl(UeHttpUrl.getChapterRead() + url);
                                                    sitBean.setLoadUrl(loadUrl);
                                                    SitRepository.getInstance().saveSit(sitBean);
                                                }else {
                                                    Thread.sleep(1000);
                                                    handler.post(runnableUis);
                                                }
                                                i = 0;
                                                break;
                                            }else{
                                                Thread.sleep(1000);
                                                i++;
                                            }
                                            if (i == 6) {//5秒结束获取失败
                                                if(mChapterSitList.size()>1) {
                                                    changeBookToc(collBookBean);
                                                    break;
                                                }else{
                                                    Thread.sleep(1000);
                                                    handler.post(runnableUis);
                                                    break;
                                                }
                                            }
                                        }
                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                }
                            }).start();

                            }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }

            });
        } catch (Exception e) {

        }
    }


    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            UeDialog.hideProgress();
            if (mChapterList != null) {
                muluNumber.setText("共" + mChapterList.size() + "章");
            }
        }

    };
    Runnable vun = new Runnable() {
        @Override
        public void run() {
            menuUpdateTx.setVisibility(View.GONE);
        }

    };
    Runnable runnableUis = new Runnable() {
        @Override
        public void run() {
            UeDialog.hideProgress();
            ToastUtils.showToast("章节未获取到，请重试");
            menuUpdateTx.setVisibility(View.VISIBLE);
        }

    };
    Runnable rUis = new Runnable() {
        @Override
        public void run() {
            UeDialog.hideProgress();
            menuUpdateTx.setVisibility(View.VISIBLE);
            ToastUtils.showToast("章节未获取到，请重试");
        }

    };
    Handler handlers=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BookDetail detail=(BookDetail)msg.obj;
            showBookDetail(detail);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //如果进入阅读页面收藏了，页面结束的时候，就需要返回改变收藏按钮
        if (requestCode == REQUEST_READ) {
            if (data == null) return;

            isJoinedCollections = data.getBooleanExtra(RESULT_IS_COLLECTED, false);

            if (isJoinedCollections) {
                mBtnJoinCollection.setText(R.string.book_detail_remove_collection);
                mBtnJoinCollection.setTextColor(Color.parseColor("#1089DC"));
                Drawable drawable = ContextCompat.getDrawable(this, R.mipmap.book_detail_info_del_img);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                mBtnJoinCollection.setBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.btn_join_collection_pressed));
                mBtnJoinCollection.setCompoundDrawables(drawable, null, null, null);
                mBtnJoinCollection.postInvalidate();
                isJoinedCollections = true;
            }
        }
    }
    public void changeBookToc(CollBookBean collBook) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                UeDialog.showprogressDialog(context, "", "正在换源中，请稍后", false);
            }
        },100);

        try {
            mOkHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(60, TimeUnit.SECONDS)       //设置连接超时
                    .readTimeout(60, TimeUnit.SECONDS)          //设置读超时
                    .writeTimeout(60, TimeUnit.SECONDS)          //设置写超时
                    .retryOnConnectionFailure(true)             //是否自动重连
                    .build();
            final Request request = new Request.Builder()
                    .url(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain)
                    .get()
                    .build();
            Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String str = response.body().string();
                    String headers[] = null;

                    try {
                        com.alibaba.fastjson.JSONObject restr = com.alibaba.fastjson.JSONObject.parseObject(str);
                        if (restr.get("failed") != null) {
                            handler.post(runnableUis);
                        } else {
                            mChapterList.clear();
                            SharedPreferencesUtil.getInstance().putString(bookId+"source"+1,"1");
                            helper = new SiteHelper(restr);
                            Map<String, Object> contexts = new HashMap<String, Object>();
                            contexts.put("aid", collBook.getAid());
                            String loadUrls;
                            if (mChapterSitList.get(1).url.indexOf("https") != -1) {
                                loadUrls = mChapterSitList.get(1).url;
                            } else {
                                if (mChapterSitList.get(1).url.indexOf("qidian.com") != -1) {
                                    loadUrls = mChapterSitList.get(1).url.replace("http", "https");
                                } else {
                                    loadUrls = mChapterSitList.get(1).url;
                                }
                            }
                            contexts = helper.executeMulu(contexts, loadUrls);
                            int i = 0;
                            while (true) {
                                Object[] chapters = (Object[]) contexts.get("chapters");
                                if (chapters != null) {
                                    for (Object o : chapters) {
                                        com.alibaba.fastjson.JSONObject cJson = (com.alibaba.fastjson.JSONObject) o;
                                        if (!cJson.getString("vip").equals("true")) {
                                            BookChapterBean chapterBean = new BookChapterBean();
                                            chapterBean.setBookId(collBook.getId());
                                            chapterBean.setAid(collBook.getAid());
                                            chapterBean.setLink(cJson.getString("url"));
                                            chapterBean.setTitle(cJson.getString("name"));
                                            mChapterList.add(chapterBean);
                                        }
                                    }
                                    i = 0;
                                    if(mChapterList.size()>0) {
                                        collBook.setBookChapters(mChapterList);
                                        BookRepository.getInstance()
                                                .saveBookChaptersWithAsync(mChapterList);
                                        SitBean sitBean = new SitBean();
                                        sitBean.setId(collBook.getId());
                                        sitBean.setUrl(UeHttpUrl.getChapterRead() + mChapterSitList.get(1).domain);
                                        sitBean.setLoadUrl(mChapterSitList.get(1).url);
                                        SitRepository.getInstance().saveSit(sitBean);
                                    }else{
                                        Thread.sleep(1000);
                                        handler.post(runnableUis);
                                    }
                                    break;
                                } else {
                                    Thread.sleep(1000);
                                    i++;
                                }
                                if (i >7) {
                                    Thread.sleep(1000);
                                    handler.post(runnableUis);
                                    break;
                                }
                            }
                        }
                    } catch (Exception e1) {
                        e1.printStackTrace();
                        handler.post(runnableUis);
                    }
                }
            });
        } catch (Exception e) {
            handler.post(runnableUis);
        }
    }

}
